package com.fengwan.wastesort.ui.fragment

import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView.VERTICAL
import com.chad.library.adapter.base.BaseQuickAdapter

import com.fengwan.wastesort.R
import com.fengwan.wastesort.adapter.WasteSortAdapter
import com.fengwan.wastesort.adapter.WasteSortAdapter2
import com.fengwan.wastesort.model.Waste
import com.fengwan.wastesort.ui.viewModel.WasteDryViewModel
import kotlinx.android.synthetic.main.fragment_waste_sort.*

class WasteDryFragment : BaseWasteFragment(), BaseQuickAdapter.RequestLoadMoreListener, Observer<List<Waste>> {

    companion object {
        fun newInstance() = WasteDryFragment()
    }

    private val adapter by lazy { WasteSortAdapter2(activity!!) }
    private val viewModel by lazy { ViewModelProviders.of(this).get(WasteDryViewModel::class.java) }
    private var isFirst = true

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_waste_sort, container, false)
    }

    override fun initListener() {
        viewModel.dryWastes.observe(this, this)
    }

    override fun loadData(_id: Int, type: Int) {
        viewModel.loadDryWastes(_id, type)
    }

    override fun onLoadMoreRequested() {
//        loadData(adapter.data[adapter.data.size - 1]._id)
    }

    override fun initView(view: View) {
        recycler.layoutManager = GridLayoutManager(context, 2, VERTICAL, false)
        val itemHeader = getItemHeader(R.layout.item_waste_header, recycler)
//        adapter.setHeaderView(itemHeader)
        setItemHeaderContent(
            itemHeader,
            R.color.colorWasteDry,
            "干垃圾",
            R.mipmap.icon_residual,
            "除其他三类垃圾外的生活废弃物\n如废弃纸巾、尿不湿、烟蒂、干燥剂、污损塑料、大骨头、硬贝壳、毛发、橡皮泥、旧毛巾、一次性餐具、镜子、陶瓷制品、竹h制品、成分复杂的制品等。\n◆易碎或已污染的、应包裹后投放\n◆投放时，应保持周边环境整洁\n◆与其他种类垃圾分开投放"
        )
//        adapter.setOnLoadMoreListener(this, recycler)
        recycler.adapter = adapter
    }

    override fun onChanged(it: List<Waste>) {
        if (it.any()) {
            if (isFirst) {
                adapter.setNewData(it)
                isFirst = false
            } else {
                adapter.addData(it)
            }
//            adapter.loadMoreComplete()
        } else {
//            adapter.loadMoreEnd(true)
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        viewModel.dryWastes.removeObserver(this)
    }

}
